-module(p35).
-compile(export_all).

main([]) -> [];
main([Head | _T]=Primes) ->
    {IsCP, PrimesToDelete} = is_circular_prime(Head, Primes),
    NextPrimes = Primes -- PrimesToDelete,
    case IsCP of
        true -> PrimesToDelete ++ main(NextPrimes);
        false -> main(NextPrimes)
    end.
    

is_circular_prime(PrimeNum, Primes) when is_number(PrimeNum) -> 
    AllRotations = [PrimeNum | Rotations] = circular_rotations(PrimeNum),
    {is_circular_prime(Rotations, Primes), AllRotations};
is_circular_prime([H | T], Primes) ->
    lists:member(H, Primes) andalso is_circular_prime(T, Primes);
is_circular_prime([], _Primes) -> true.
    

circular_rotations(Num) -> 
    NumAsList = erlang:integer_to_list(Num),
    circular_rotations(NumAsList, []).

circular_rotations(NumAsList, Rotation) -> 
    case Rotation of 
        [] -> [erlang:list_to_integer(NumAsList) | 
            circular_rotations(NumAsList, next_rotation(NumAsList))];
        NumAsList -> [];
        _O -> [erlang:list_to_integer(Rotation) | 
            circular_rotations(NumAsList, next_rotation(Rotation))]
    end.
    
next_rotation([Head | List]) -> List ++ [Head].
